import React, { useCallback, useEffect, useRef, useState } from 'react';
import { v4 as uuid } from 'uuid';

function Intersection({
  children,
  root = null,
  rootMargin = '10px 10px 10px 10px',
  threshold = 0.2,
}) {
  // 被监听元素
  const domRef = useRef<any>(null);
  const [intersection, setIntersection] = useState<boolean>(false);
  // 判断是否已经加载
  const loadIdRef = useRef<string>('');
  // IntersectionObserver构造函数的回调
  const callBack = useCallback(
    (entries) => {
      // 如果 intersectionRatio 为 0，则目标在视野外，
      // 我们不需要做任何事情。
      const e = entries[0];
      const id = e.target.getAttribute('id');
      if (e.intersectionRatio > 0 || e.isIntersecting) {
        loadIdRef.current = id;
        setIntersection(true);
        // 销毁监听元素
        intersectionObserver.current.unobserve(domRef.current);
      } else if (loadIdRef.current !== id) {
        setIntersection(false);
      }
    },
    [intersection, setIntersection],
  );
  const intersectionObserver = useRef<any>(null);
  const watchLis = () => {
    intersectionObserver.current = new IntersectionObserver(callBack, {
      root,
      rootMargin,
      threshold,
    });
    // 开始监听
    intersectionObserver.current.observe(domRef.current);
  };
  useEffect(() => {
    watchLis();
  }, []);
  return (
    <div style={{ width: '100%', height: '100%' }} id={uuid()}>
      <div style={{ width: '100%', height: '100%' }} ref={domRef}>
        {intersection ? children : null}
      </div>
    </div>
  );
}

export default Intersection;


// 使用方法
import Intersection from '@/components/intersection';
<Intersection rootMargin="10px 10px 10px 10px" root={root}>
<div>
    {/* balabala */}
</div>
</Intersection>